<!-- pages/contacts/add.vue -->
<template>
  <view class="container">
    <view class="form-card">
      <view class="form-item">
        <text class="label">姓名</text>
        <input v-model="form.name" class="input" placeholder="请输入姓名" />
      </view>
      <view class="form-item">
        <text class="label">电话</text>
        <input 
          v-model="form.phone" 
          class="input" 
          placeholder="请输入手机号"
          type="number"
        />
      </view>
      <view class="form-item">
        <text class="label">部门</text>
        <picker 
          @change="bindPickerChange" 
          :value="departmentIndex" 
          :range="departments"
        >
          <view class="picker">
            {{ departments[departmentIndex] || '请选择部门' }}
          </view>
        </picker>
      </view>
      <button class="submit-btn" @click="handleSubmit">保存联系人</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref } from 'vue';

const form = reactive({
  name: '',
  phone: '',
  department: ''
});

const departments = ['技术部', '市场部', '人事部', '财务部', '行政部'];
const departmentIndex = ref(0);

const bindPickerChange = (e) => {
  departmentIndex.value = e.detail.value;
  form.department = departments[departmentIndex.value];
};

const handleSubmit = async () => {
  if (!form.name || !form.phone) {
    uni.showToast({ title: '请填写完整信息', icon: 'none' });
    return;
  }

  // 生成随机头像
  const randomAvatar = `/static/avatars/avatar-${Math.floor(Math.random() * 6) + 1}.png`;
  
  // // 获取现有联系人
  // const { data } = await uni.getStorage({ key: 'contacts' });
  const contacts =  [];
  
  // 添加新联系人
  contacts.push({
    id: Date.now(),
    ...form,
    avatar: randomAvatar
  });

  // 保存数据
  await uni.setStorage({ key: 'contacts', data: contacts });
  
  uni.showToast({ title: '添加成功' });
  // setTimeout(() => uni.navigateBack(), 1500);
};
</script>

<style lang="scss" scoped>
.container {
  padding: 40rpx;
  min-height: 100vh;
  background: #f5f5f5;
}

.form-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.form-item {
  margin-bottom: 40rpx;
  .label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
  }
  
  .input, .picker {
    height: 80rpx;
    padding: 0 20rpx;
    border: 1rpx solid #eee;
    border-radius: 10rpx;
    font-size: 28rpx;
  }
}

.submit-btn {
  margin-top: 60rpx;
  background: #007AFF;
  color: #fff;
  border-radius: 50rpx;
  height: 90rpx;
  line-height: 90rpx;
}
</style>